<template>
  <div class="audio-config">
    <a-form :model="formState" layout="vertical">
      <!-- 音频输入选项已隐藏 -->
      <!--
      <a-form-item label="启用音频输入" name="enable">
        <a-switch v-model:checked="formState.enable" />
      </a-form-item>

      <a-divider>音频输入源</a-divider>

      <a-form-item label="输入设备" name="inputSource">
        <a-select
          v-model:value="formState.inputSource"
          @change="handleInputSourceChange"
          :loading="loadingDevices"
        >
          <a-select-option value="builtin">内置麦克风</a-select-option>
          <a-select-option value="usb">USB麦克风</a-select-option>
        </a-select>
        <div class="note">
          <span v-if="formState.inputSource === 'builtin'">
            使用设备内置麦克风采集音频
          </span>
          <span v-else>
            使用USB音频设备采集音频
          </span>
        </div>
      </a-form-item>

      <a-form-item v-if="usbDevices.length > 0">
        <a-alert
          message="已检测到USB音频设备"
          :description="`找到 ${usbDevices.length} 个USB音频设备`"
          type="info"
          show-icon
        />
      </a-form-item>
      -->

      <a-divider>音频采集参数</a-divider>

      <a-form-item label="输入音量" name="inputVolume">
        <a-slider v-model:value="formState.inputVolume" :min="0" :max="100" />
      </a-form-item>

      <a-form-item label="采样率" name="sampleRate">
        <a-select v-model:value="formState.sampleRate" disabled>
          <a-select-option :value="16000">16000 Hz</a-select-option>
        </a-select>
        <div class="note">音频固定为PCM（16kHz、16bit、单声道），不可修改</div>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSubmit" :loading="submitting">保存设置</a-button>
          <a-button @click="handleReset">重置</a-button>
          <a-button @click="refreshDevices" :loading="loadingDevices">刷新设备</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getAudioInputDevices } from '@/api/audio';
import { getAudioInputSource, setAudioInputSource } from '@/api/config';

const formState = reactive({
  enable: true,
  inputSource: 'builtin',
  inputVolume: 80,
  sampleRate: 16000
});

const usbDevices = ref([]);
const loadingDevices = ref(false);
const submitting = ref(false);

// 加载音频输入设备列表
const loadAudioDevices = async () => {
  try {
    loadingDevices.value = true;
    const response = await getAudioInputDevices();

    // handleResponse 已经提取了 result 层，response 就是结果对象
    if (response && response.devices) {
      // 过滤出USB设备
      usbDevices.value = response.devices.filter(
        device => device.type === 'usb' && device.is_connected
      );
      console.log('USB音频设备:', usbDevices.value);
    }
  } catch (error) {
    console.error('加载音频设备失败:', error);
    message.error('加载音频设备失败');
  } finally {
    loadingDevices.value = false;
  }
};

// 加载当前音频输入源
const loadCurrentInputSource = async () => {
  try {
    const response = await getAudioInputSource();

    // handleResponse 已经提取了 result 层，response 就是结果对象
    if (response) {
      // config.get 返回的是整个 audio_input 配置对象
      const source = response.source || 'usb';

      if (source === 'usb') {
        formState.inputSource = 'usb';
      } else {
        formState.inputSource = 'builtin';
      }

      console.log('当前音频输入源:', response);
    }
  } catch (error) {
    console.error('加载当前音频输入源失败:', error);
  }
};

// 刷新设备列表
const refreshDevices = async () => {
  await loadAudioDevices();
  message.success('设备列表已刷新');
};

// 输入源变化处理
const handleInputSourceChange = (value) => {
  console.log('音频输入源已变更:', value);
};

// 保存设置
const handleSubmit = async () => {
  try {
    submitting.value = true;

    // 确定音频源类型（只允许builtin或usb）
    let source = formState.inputSource;

    if (source !== 'builtin' && source !== 'usb') {
      // 如果不是预定义的值，默认设为usb
      source = 'usb';
    }

    // 调用API设置音频输入源（只设置source字段）
    const response = await setAudioInputSource(source);

    // handleResponse 已经提取了 result 层，response 就是结果对象
    // 检查返回的 status 字段来确认是否成功
    if (response && response.status === 'success') {
      message.success('音频设置已保存');
      // 重新加载当前音频源以确认
      await loadCurrentInputSource();
    } else {
      message.error('保存失败，请重试');
    }
  } catch (error) {
    console.error('保存音频设置失败:', error);
    message.error('保存失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 重置设置
const handleReset = () => {
  formState.enable = true;
  formState.inputSource = 'builtin';
  formState.inputVolume = 80;
  formState.sampleRate = 16000;
  message.info('已重置为默认音频设置');
};

// 组件挂载时加载数据
onMounted(async () => {
  await loadAudioDevices();
  await loadCurrentInputSource();
});
</script>

<style scoped>
.audio-config {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.note {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style> 
